<?php

declare(strict_types=1);

namespace Newbie\Exception\Handler;


use Newbie\Exception\CaptchaException;
use Newbie\Exception\NewbieException;
use Newbie\Exception\NoPermissionException;
use Newbie\Exception\NormalStatusException;
use Newbie\Exception\TokenException;
use Newbie\Exception\UserBanException;
use support\Response;
use Throwable;
use Webman\Http\Request;

class AppExceptionHandler extends \Webman\Exception\ExceptionHandler {

    public $dontReport = [
        NormalStatusException::class,
        NoPermissionException::class,
        CaptchaException::class,
        TokenException::class,
        UserBanException::class
    ];

    public function render (Request $request, Throwable $exception): \Webman\Http\Response {
        $code = $exception->getCode();
        if ($request->expectsJson()) {
            $json = ['code' => $code ?: 500, 'success' => false, 'message' => $this->debug ? $exception->getMessage() : 'Server internal error'];
            $this->debug && $json['traces'] = (string)$exception;
            return new Response(200, ['Content-Type' => 'application/json'],
                json_encode($json, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
        }
        $error = $this->debug ? nl2br((string)$exception) : 'Server internal error';
        return new Response(500, [], $error);
    }

    public function isNorNormalException (\Throwable $exception) {
        foreach ($this->dontReport as $e) {
            if ($exception instanceof $e) {
                return true;
            }
        }
    }


}
